import {routers} from "@/router";

const VISITED_VIEWS = 'VISITED_VIEWS'

const app = {
    state: {
        sidebar: true,
        visitedViews: [],
        loggerSelection: {
            type: null,
            items: null,
            action: false
        }
    },
    mutations: {
        TOGGLE_SIDEBAR: state => {
            state.sidebar = !state.sidebar
        },
        LOGGER_SELECTION(state, logger) {
            state.loggerSelection = Object.assign(state.loggerSelection, logger)
        },
        ADD_VISITED_VIEWS: (state, view) => {
            if (state.visitedViews.some(v => v.path === view.path)) return
            state.visitedViews.push({ name: view.name, path: view.path })

            window.sessionStorage.setItem(VISITED_VIEWS, JSON.stringify(state.visitedViews))
        },
        DEL_VISITED_VIEWS: (state, view) => {
            let index
            for (const [i, v] of state.visitedViews.entries()) {
                if (v.path === view.path) {
                    index = i
                    break
                }
            }
            state.visitedViews.splice(index, 1)
        },
        RELOAD_VISITED_VIEWS: (state) => {
            const vv = window.sessionStorage.getItem(VISITED_VIEWS)
            if(vv != null) state.visitedViews = JSON.parse(vv)
        },
        CLEAR_VISITED_VIEWS: (state, view) => {
            state.visitedViews = []
        },
    },
    actions: {
        ToggleSideBar({ commit }) {
            commit('TOGGLE_SIDEBAR')
        },
        addVisitedViews({ commit }, view) {
            commit('ADD_VISITED_VIEWS', view)
        },
        delVisitedViews({ commit, state }, view) {
            return new Promise((resolve) => {
                commit('DEL_VISITED_VIEWS', view)
                resolve([...state.visitedViews])
            })
        },
        ReloadVisitedViews({ commit }) {
            return new Promise((resolve) => {
                commit('RELOAD_VISITED_VIEWS')
                resolve()
            })

        }
    }
}

export default app
